<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="昵称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入昵称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="拓聊号" prop="cloudId">
        <el-input
          v-model="queryParams.cloudId"
          placeholder="请输入拓聊号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="vipStatus">
        <el-select v-model="queryParams.vipStatus" placeholder="请选择" clearable  size="small">
          <el-option
            v-for="dict in vipStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['model:user:add']"
        >新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['model:user:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column label="用户id" align="center" prop="id" />
      <el-table-column label="昵称" align="center" prop="nickName" show-overflow-tooltip />
      <el-table-column label="拓聊号" align="center" prop="cloudId" />
      <el-table-column label="头像" align="center" prop="headImg" >
        <template slot-scope="scope">
          <el-avatar shape="square" :src="scope.row.headImg" :style="randomRgb()" :size="30">
            {{scope.row.nickName}}
          </el-avatar>
        </template>
      </el-table-column>
      <!--<el-table-column label="token" align="center" prop="token" />-->
      <!--<el-table-column label="融云token" align="center" prop="cloudToken" />-->
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="会员状态" align="center" prop="vipStatus" :formatter="vipStatusFormat" />
      <el-table-column label="钱包余额" align="center" prop="money" >
        <template slot-scope="scope">
          <span>{{towNumber(scope.row.money) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="会员结束时间" align="center" prop="vipEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.vipEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column label="密码" align="center" prop="password" />-->
      <!--<el-table-column label="盐值" align="center" prop="salt" />-->
      <el-table-column label="上次登录时间" align="center" prop="loginTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.loginTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240px" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['model:user:edit']"
          >修改</el-button>
          <!--<el-button-->
            <!--size="mini"-->
            <!--type="text"-->
            <!--icon="el-icon-circle-plus-outline"-->
            <!--@click="handleRecharge(scope.row)"-->
            <!--v-hasPermi="['model:user:remove']"-->
          <!--&gt;充值</el-button>-->
          <el-button
            size="mini"
            type="text"
            @click="handleBan(scope.row)"
            v-hasPermi="['model:user:remove']"
          ><span v-text="scope.row.ban === 1?'解封':'封禁'"></span></el-button>
          <el-button
            size="mini"
            type="text"
            @click="getGroupsList(scope.row)"
            v-hasPermi="['model:user:edit']"
          >所在群</el-button>
          <!--<el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['model:user:remove']"
          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="手机号" prop="phone">
          <el-input :disabled="form.id!=null" maxlength="11"  v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="登陆密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="支付密码" prop="passwordPay">
          <el-input v-model="form.passwordPay" placeholder="请输入支付密码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 充值对话框 -->
    <!--<el-dialog title="充值" :visible.sync="rechargeForm.open" width="500px" append-to-body>-->
      <!--<el-form ref="rechargeForm" :model="rechargeForm" :rules="rechargeRules" label-width="80px">-->
        <!--<el-form-item label="充值金额" prop="money">-->
          <!--<el-input v-model="rechargeForm.money" type="number" placeholder="请输入金额" />-->
        <!--</el-form-item>-->
      <!--</el-form>-->
      <!--<div slot="footer" class="dialog-footer">-->
        <!--<el-button type="primary" @click="submitRechargeForm">确 定</el-button>-->
        <!--<el-button @click="cancel">取 消</el-button>-->
      <!--</div>-->
    <!--</el-dialog>-->

    <!-- 所在群对话框 -->
    <el-dialog title="所在群" :visible.sync="openGroup" width="600px" append-to-body>
      <el-table v-loading="loadingGroup" :data="groupList">
        <el-table-column label="群id" align="center" prop="id" />
        <el-table-column label="群名称" align="center" prop="name" show-overflow-tooltip/>
        <el-table-column label="角色" align="center" prop="role"  :formatter="roleFormat"/>
      </el-table>
      <pagination
        v-show="totalGroup>0"
        :total="totalGroup"
        :page-sizes="[8,16]"
        :page.sync="queryGroupParams.pageNum"
        :limit.sync="queryGroupParams.pageSize"
        @pagination="getGroupsList"
      />
    </el-dialog>
  </div>
</template>

<style>
  .el-avatar{
    margin-top: 6px;
  }

  .el-dialog{
    display: flex;
    flex-direction: column;
    margin:0 !important;
    position:absolute;
    top:35%;
    left:50%;
    transform:translate(-50%,-50%);
    /*height:600px;*/
    max-height:calc(100% - 30px);
    max-width:calc(100% - 30px);
  }
  .el-dialog .el-dialog__body{
    flex:1;
    overflow: auto;
  }
</style>

<script>
import { listUser,selectGroups, getUser, delUser, addUser, updateUser,banUser, exportUser,recharge } from "@/api/model/user";

export default {
  name: "User",
  data() {
    var checkMoney = (rule, value, callback) => {
        if (value < 0.01) {
          callback(new Error('最小金额为0.01'))
        } else {
          callback()
        }
    };
    return {
      // 遮罩层
      loading: true,
      loadingGroup: true,
      // 选中数组
      ids: [],
      userId: undefined,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      totalGroup: 0,
      // 用户信息表格数据
      userList: [],
      groupList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openGroup: false,
      //会员状态
      vipStatusOptions: [],
      roleOptions: ['群主','管理员','普通成员'],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: undefined,
        phone: undefined,
        cloudId: undefined,
      },
      // 查询参数
      queryGroupParams: {
        pageNum: 1,
        pageSize: 8,
      },
      baseUrl:process.env.VUE_APP_BASE_API,
      // 表单参数
      form: {},
      beforeForm: {
        nickName: undefined,
        passwordPay: undefined,
        password: undefined,
      },
      rechargeForm: {
        open:false,
        userId:undefined,
        money:undefined
      },
      // 表单校验
      rules: {
        phone:{required:true,message:"请填入手机号", trigger: 'blur'},
        nickName:{required:true,message:"请填入昵称", trigger: 'blur'},
      },
      // 表单校验
      rechargeRules: {
        money:[
          {required:true,message:"请填入充值金额", trigger: 'blur'},
          {validator: checkMoney, trigger: 'blur'},
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("vip_status").then(response => {
      this.vipStatusOptions = response.data;
    });
  },
  methods: {
    /** 查询用户信息列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询用户所在群 */
    getGroupsList(row) {
      this.loadingGroup = true;
      this.openGroup = true;
      if(row.id!=null){
        this.userId = row.id;
      }
      selectGroups(this.userId,this.queryGroupParams).then(response => {
        this.groupList = response.rows;
        this.totalGroup = response.total;
        this.loadingGroup = false;
      });
    },
    roleFormat(row, column) {
      return this.roleOptions[row.role];
    },
    //随机头像背景颜色
    randomRgb(item) {
      let R = Math.floor(Math.random() * 130+110);
      let G = Math.floor(Math.random() * 130+110);
      let B = Math.floor(Math.random() * 130+110);
      return {
        'background-color': 'rgb(' + R + ',' + G + ',' + B + ')'
      };
    },
    //格式化金额显示
    towNumber(val) {
      if(val==null||val === ''){
        return "";
      }
      return val.toFixed(2)
    },
    // 状态:0-正常;5-删除字典翻译
    vipStatusFormat(row, column) {
      return this.selectDictLabel(this.vipStatusOptions, row.vipStatus);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openGroup = false;
      this.rechargeForm.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        nickName: undefined,
        phone: undefined,
        password: undefined,
        passwordPay: undefined,
        createTime: undefined,
        loginTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户信息";
      this.form.nickName = this.beforeForm.nickName;
      this.form.password = this.beforeForm.password;
      this.form.passwordPay = this.beforeForm.passwordPay;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getUser(id).then(response => {
        this.form = response.data;
        this.form.password = null;
        this.form.passwordPay = null;
        this.open = true;
        this.title = "修改用户信息";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUser(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            if(this.form.password==null||this.form.password===''){
              this.msgError("请输入登陆密码");
              return;
            }
            if(this.form.passwordPay==null||this.form.passwordPay===''){
              this.msgError("请输入支付密码");
              return;
            }
            this.beforeForm.nickName = this.form.nickName;
            this.beforeForm.password = this.form.password;
            this.beforeForm.passwordPay = this.form.passwordPay;
            addUser(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 充值提交按钮 */
    submitRechargeForm: function() {
      this.$refs["rechargeForm"].validate(valid => {
        if (valid) {
          recharge(this.rechargeForm).then(res=>{
            if (res.code === 200) {
              this.msgSuccess("充值成功");
              this.rechargeForm.open = false;
              this.getList();
            }else {
              this.msgError(res.msg);
            }
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除用户信息编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delUser(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 充值按钮操作 */
    handleRecharge(row) {
      this.rechargeForm.open = true;
      this.rechargeForm.userId = row.id;
      this.rechargeForm.money = undefined;
    },
    /** 充值按钮操作 */
    handleBan(row) {
      if(row.ban === 0){
        this.$prompt('输入封禁原因', '封禁', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({ value }) => {
          const data = {
            id:row.id,
            ban:1,
            banDesc:value
          }
          banUser(data).then(response => {
            this.msgSuccess("操作成功");
            this.getList();
          });
        });
      }
      if(row.ban === 1){
        const data = {
          id:row.id,
          ban:0
        }
        banUser(data).then(response => {
          this.msgSuccess("操作成功");
          this.getList();
        });
      }


    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有用户信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportUser(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>
